import React, { useRef, useEffect } from 'react';
import echarts from 'echarts';
import 'echarts/lib/chart/bar';

interface IBarData {
  data: { name: string; value: number; [propName: string]: any }[];
}

interface IBarProps {
  yLabel: string[]; // y轴标签
  data: IBarData['data']; // 数据
  onClick: (data: IBarData['data']) => void;
}

function Bar(props: IBarProps) {
  const divEl = useRef(null);
  const { yLabel, data, onClick } = props;
  const shadowData = new Array(data.length).fill(100);
  const option: echarts.EChartOption = {
    grid: {
      top: 20,
      left: 0,
      right: 40,
      bottom: 0,
      containLabel: true
    },
    xAxis: {
      type: 'value',
      show: false
    },
    yAxis: {
      type: 'category',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#696C78',
        fontSize: 14,
        inside: true,
        verticalAlign: 'bottom',
        lineHeight: 35
      },
      data: yLabel
    },
    series: [
      {
        type: 'bar',
        name: 'data',
        z: 2,
        itemStyle: {
          color: '#FF0000'
        },
        barWidth: 12,
        data
      },
      {
        type: 'bar',
        z: 1,
        label: {
          show: true,
          color: '#696C78',
          position: 'right',
          formatter: ({ dataIndex }: { dataIndex: number }) => data[dataIndex].value
        },
        itemStyle: {
          color: '#EFF4FE'
        },
        emphasis: {
          itemStyle: {
            color: '#EFF4FE'
          }
        },
        barWidth: 12,
        barGap: '-100%',
        data: shadowData
      }
    ]
  };
  useEffect(() => {
    const lineDom = echarts.init(divEl.current!);
    lineDom.off('click');
    lineDom.setOption(option);
    lineDom.on('click', ({ data: d }: IBarData) => {
      onClick(d);
    });
  });
  return <div ref={divEl} style={{ width: '100%', height: '100%' }} />;
}

export default Bar;
